/*
 * 描          述:  <描述>
 * 修  改   人:  brady
 * 修改时间:  2013-8-27
 * <修改描述:>
 */
package com.tx.core.generator.model.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.tx.core.ddlutil.dialect.Dialect4DDL;
import com.tx.core.ddlutil.helper.JPAEntityDDLHelper;
import com.tx.core.ddlutil.model.JPAEntityColumnDef;
import com.tx.core.ddlutil.model.JdbcTypeEnum;
import com.tx.core.ddlutil.model.TableColumnDef;
import com.tx.core.ddlutil.model.TableDef;
import com.tx.core.ddlutil.model.TableIndexDef;
import com.tx.core.exceptions.util.AssertUtils;
import com.tx.core.generator.model.DBScriptGenModel;
import com.tx.core.generator.model.EntityProperty;
import com.tx.core.generator.util.JPAGeneratorUtils;
import com.tx.core.util.TableInfoUtils;

/**
 * 数据脚本映射<br/>
 * <功能详细描述>
 *
 * @author brady
 * @version [版本号, 2013-8-27]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class JPADBScriptGeneratorModel implements DBScriptGenModel {

	private final String comment;

	private final String tableName;

	private final TableDef tableDef;
	
	private final String primaryKey;

	private final List<EntityProperty> propertyList;

	private final List<TableIndexDef> indexDefs = new ArrayList<>();

	/**
	 * 默认构造函数
	 */
	public JPADBScriptGeneratorModel(Class<?> entityType, Dialect4DDL ddlDialect) {
		super();
		TableDef td = JPAEntityDDLHelper.analyzeToTableDefDetail(entityType, ddlDialect);

		this.tableDef = td;
		this.tableName = td.getName();
		this.comment = td.getComment();
		this.indexDefs.addAll(td.getIndexes());

		Map<String, TableColumnDef> cmap = new HashMap<>();
		td.getColumns().stream().forEach(c -> {
			cmap.put(c.getName().toUpperCase(), c);
		});
		this.propertyList = JPAGeneratorUtils.parseEntityPropertyList(entityType).stream().map(column -> {
			return column;
		}).collect(Collectors.toList());

		this.primaryKey = td.getPrimaryKey();
		this.indexDefs.addAll(td.getIndexes());
		for (EntityProperty ep : this.propertyList) {
			TableColumnDef tcd =cmap.get(ep.getColumnName().toUpperCase());
			AssertUtils.notNull(tcd, "tcd is null. columName:" + ep.getColumnName());
			
			String columnType = ddlDialect.getDialect().getTypeName(tcd.getJdbcType().sqlType, tcd.getSize(),
					tcd.getSize(), tcd.getScale());
			ep.setColumnType(columnType);
		}
	}

	/**
	 * @return 返回 tableName
	 */
	public String getTableName() {
		return this.tableName;
	}

	/**
	 * @return 返回 comment
	 */
	public String getComment() {
		return comment;
	}

	/**
	 * @return 返回 primaryKey
	 */
	public String getPrimaryKey() {
		return this.primaryKey;
	}

	/**
	 * @return 返回 tableDef
	 */
	public TableDef getTableDef() {
		return tableDef;
	}

	/**
	 * @return 返回 indexDefs
	 */
	public List<? extends TableIndexDef> getIndexDefs() {
		return indexDefs;
	}


	public List<EntityProperty> getPropertyList() {
		return propertyList;
	}

}
